package com.example.fieldnotes;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ShareActionProvider;
import android.widget.Spinner;
import android.widget.TextView;

@SuppressWarnings("unused")
public class MainActivity extends Activity {
	private static final int REQUEST_LINK_TO_DBX = 0;
	private ShareActionProvider mShareActionProvider;
	private Button nextRange, backRange, nextRow, backRow, save, back;
	private CheckBox shedding;
	private Spinner rowChoice, rangeChoice, phenoChoice;
	private TextView row, range, currentData, dateText;
	private DatePicker date;
	private int nRange = -1, nRow = 2, optionChoice, month = 5, day = 26, year = 2013;
	private String[] ranges = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S"};
	private String[] alphabet = {"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "X", "Y", "Z"};
	private String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	private dataStuff data;
	private int sRow, eRow, sRange, eRange;
	private SharedPreferences pref;
	private Save MagicDocument;
	private String[][] bridge;
	private Editor edit;
	private boolean loaded = false;
	private AlertDialog alertDialog;
	private SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
	private String newFileName = "", currentDate = sdf.format(new Date()), sDate, eDate;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Bundle extras = getIntent().getExtras();
		
		try {
			pref = getSharedPreferences("Options", 0);
			loaded = pref.getBoolean("loaded", false);
			//System.out.println(loaded);
			
			rowChoice = (Spinner)findViewById(R.id.rowSpinner);
			rowChoice.setSelection(0);
			rangeChoice = (Spinner)findViewById(R.id.rangeSpinner);
			rangeChoice.setSelection(0);
			phenoChoice = (Spinner)findViewById(R.id.phenotypes);
			phenoChoice.setSelection(0);
			
			//for anthesis entries
			date = (DatePicker)findViewById(R.id.datePicker1);
			
			shedding = (CheckBox)findViewById(R.id.shedding);
			shedding.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (shedding.isChecked())
					{
						month = date.getMonth();
						day = date.getDayOfMonth();
						year = date.getYear();
						setDate(month, day, year);
						date.updateDate(year, month, day);
						shedding.setChecked(true);
					}
					else
					{
						//data.add(nRange, nRow, "0");
						date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
						shedding.setChecked(false);
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
			});
			
			dateText = (TextView)findViewById(R.id.date);
			
			row = (TextView)findViewById(R.id.rowCurrent);
			row.setText(""+(nRow));
			
			range = (TextView)findViewById(R.id.rangeCurrent);
			nRange++;
			range.setText(ranges[nRange]);
			
			currentData = (TextView)findViewById(R.id.data);
			newFileName = pref.getString("stringIn", "");
			
			//Set settings
			edit = pref.edit();
			edit.putString("stringIn", "");
			edit.putString("previous", newFileName);
			edit.commit();
	
			sRow = pref.getInt("sRow", 1);
			eRow = pref.getInt("eRow", 10) + 1;
			
			sRange = pref.getInt("sRange", 0);
			eRange = pref.getInt("eRange", 5);
			
			sDate = pref.getString("sDate", "01/01/1980");
			eDate = pref.getString("eDate", "12/31/2079");
			
			optionChoice = pref.getInt("choice", -1);
			////System.out.println(newFileName + "::" + optionChoice);
			
			if (!loaded)
			{
				data = new dataStuff(pref, eRange+1, eRow, optionChoice, newFileName, this);
				////System.out.println("this should always print first");
				finish();
			}
			else
			{
				int count = this.getIntent().getIntExtra("size", 20);
				bridge = new String[count][];
				
				for (int i = 0; i < count; i++)
				{
					bridge[i] = this.getIntent().getStringArrayExtra("data" + i);
				}
				
				edit.putBoolean("loaded", false);
				edit.commit();
				
				data = new dataStuff(bridge, count, eRow);
			}
			
			if (data.isRightFormat() != 1)
			{
				this.finish();
			}
			
			if (optionChoice == 0)
			{
				//Basic note taking chosen
				if (newFileName.matches(""))
					newFileName = "notes.xls";
				
				currentData.setVisibility(View.VISIBLE);
			}
			else if (optionChoice == 1)
			{
				//Lesion Scoring chosen
				if (newFileName.matches(""))
					newFileName = "rating.xls";
				
				findViewById(R.id.option2).setVisibility(View.VISIBLE);
				////System.out.println(newFileName + "file");
			}
			else if (optionChoice == 2)
			{
				//Anthesis Dates chosen
				if (newFileName.matches(""))
					newFileName = "notes.xls";
				
				findViewById(R.id.option3).setVisibility(View.VISIBLE);
				shedding.setVisibility(0);
			}
			else if (optionChoice == 3)
			{
				
			}
			
			////System.out.println(data.get(0, 0) + data.get(0, 1) + data.get(0, 2));
			////System.out.println(data.get(1, 0) + data.get(1, 1) + data.get(1, 2));
			////System.out.println(data.get(2, 0) + data.get(2, 1) + data.get(2, 2));
			currentData.setText("" + data.get(1, 0));
			
			MagicDocument = new Save(optionChoice, newFileName, pref);
			
			setUpSpinners(optionChoice);
			setUpButton(optionChoice);
		} catch (NullPointerException e) {
			edit.putBoolean("loaded", false);
			edit.commit();
		}
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		super.onCreateOptionsMenu(menu);
		MenuInflater myMenu = getMenuInflater();
		myMenu.inflate(R.menu.main, menu);
		return true;
	}
	
	private void setShareIntent(Intent shareIntent) {
	    if (mShareActionProvider != null) {
	        mShareActionProvider.setShareIntent(shareIntent);
	    }
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
		String title = (String) item.getTitle();
		////System.out.println((title=(String) item.getTitle()));
        
		if (title.matches("Settings"))
		{
            Intent i = new Intent(MainActivity.this, Settings.class);
            finish();
            startActivity(i);
		}
		else if (title.matches("Share to..."))
		{
			shareIt();
		}
		else
		{
			//nothing
        }
 
        return false;
    }
	
	private void shareIt() {
		// TODO Auto-generated method stub
		File sdCard = Environment.getExternalStorageDirectory();
	    File directory = new File (sdCard.getAbsolutePath() + "/MAGICStuff");
	    newFileName = pref.getString("stringIn", "");
	    ////System.out.println(directory.toString() + newFileName);
	    directory.mkdir();
	    
	    File file = new File(directory, newFileName);
	    
		Intent sharingIntent = new Intent(Intent.ACTION_SEND);
		sharingIntent.setType("text/plain");
		sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
		startActivity(Intent.createChooser(sharingIntent, "Save to..."));
	}

	public void setUpSpinners(final int choice)
	{
		if (choice == 1)
		{
			String[] phenos = new String[11];
		
			for (int i = 0; i < 11; i++)
			{
				phenos[i] = "" + (i);
			}
			
			ArrayAdapter<?> phenoArrayAdapter = new ArrayAdapter<Object>(this,
			          android.R.layout.simple_spinner_item, phenos);
			phenoChoice.setAdapter(phenoArrayAdapter);
			
			try {
				phenoChoice.setSelection(Integer.parseInt(data.get(nRange, nRow)));
			}
			catch (Exception e)
			{
				phenoChoice.setSelection(0);
			}
			
			phenoChoice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
					MagicDocument.add(nRange, nRow, data);
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {
					// TODO Auto-generated method stub
					
				}
			});
		}
		else if (choice == 2)
		{
			String temp = data.get(1, 0);
			//System.out.println(temp.length() + ":");
			if (temp != null && (!temp.matches("01/01/1980") && !(temp.length() == 1)))
			{
				month = Integer.parseInt(temp.substring(0, temp.indexOf("/"))) - 1;
				temp = temp.substring(temp.indexOf("/") + 1);
				day = Integer.parseInt(temp.substring(0, temp.indexOf("/")));
				temp = temp.substring(temp.indexOf("/") + 1);
				year = Integer.parseInt(temp);
				setDate(month, day, year);
				date.updateDate(year, month, day);
				shedding.setChecked(true);
			}
			else
			{
				//data.add(nRange, nRow, "0");
				if (temp.matches("0"))
					date.updateDate(1980, 01, 01);
				else
					date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
				
				shedding.setChecked(false);
			}
			
			dateText.setText(data.get(nRange, nRow));
		}
		
		//v This line is literal magic...
		eRow--;
		
		String[] rows = new String[eRow];
		int count = 1;

		for (int i = 0; i < eRow; i++)
		{
			rows[i] = "" + count++;
			////System.out.println("number: " + i);
		}
		
		eRow++;
		//^ ...as is this...
		
		ArrayAdapter<?> rowArrayAdapter = new ArrayAdapter<Object>(this,
		          android.R.layout.simple_spinner_item, rows);
		rowChoice.setAdapter(rowArrayAdapter);
		
		rowChoice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				try {
					if (choice == 0)
						data.add(nRange, nRow, currentData.getText().toString());
					else if (choice == 1)
						data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
					else if (choice == 2)
					{
						if (shedding.isChecked())
						{
							month = date.getMonth();
							day = date.getDayOfMonth();
							year = date.getYear();
							
							setDate(month, day, year);
						}
						else
						{
							data.add(nRange, nRow, "01/01/1980");
						}
						
						dateText.setText(data.get(nRange, nRow));
					}
					
					MagicDocument.add(nRange, nRow, data);
					
					if ((nRow = Integer.parseInt(rowChoice.getSelectedItem().toString())) > 0 && nRow <= eRow)
					{
						if (choice == 0)
							currentData.setText(data.get(nRange, nRow));
						else if (choice == 1)
						{
							if (data.get(nRange, nRow) != null && !data.get(nRange, nRow).toString().matches(""))
								phenoChoice.setSelection(Integer.parseInt(data.get(nRange, nRow).toString()));
							else
								phenoChoice.setSelection(0);
						}
						else if (choice == 2)
						{
							String temp = data.get(nRange, nRow);
							
							if (temp != null && (!temp.matches("01/01/1980") && !(temp.length() == 1)))
							{
								month = Integer.parseInt(temp.substring(0, temp.indexOf("/"))) - 1;
								temp = temp.substring(temp.indexOf("/") + 1);
								day = Integer.parseInt(temp.substring(0, temp.indexOf("/")));
								temp = temp.substring(temp.indexOf("/") + 1);
								year = Integer.parseInt(temp);
								setDate(month, day, year);
								date.updateDate(year, month, day);
								shedding.setChecked(true);
							}
							else
							{
								//data.add(nRange, nRow, "0");
								if (temp.matches("0"))
									date.updateDate(1980, 01, 01);
								else
									date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
								
								shedding.setChecked(false);
							}
							
							dateText.setText(data.get(nRange, nRow));
						}
					}
					else
					{
						//System.out.println("not in range");
					}
				}
				catch (Exception e)
				{
					//System.out.println(e);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});

		ranges = new String[eRange];
		
		for (int i = 0; i < eRange; i++)
		{
			ranges[i] = alphabet[i];
		}
		
		ArrayAdapter<?> rangeArrayAdapter = new ArrayAdapter<Object>(this,
		          android.R.layout.simple_spinner_item, ranges);
		rangeChoice.setAdapter(rangeArrayAdapter);
		
		rangeChoice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				String temp = rangeChoice.getSelectedItem().toString();
				
				for (int i = 0; i < ranges.length; i++)
				{
					if (ranges[i].matches(temp))
					{
						if (choice == 0)
							data.add(nRange, nRow, currentData.getText().toString());
						else if (choice == 1)
							data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
						else if (choice == 2)
						{
							if (shedding.isChecked())
							{
								month = date.getMonth();
								day = date.getDayOfMonth();
								year = date.getYear();
								
								setDate(month, day, year);
							}
							else
							{
								data.add(nRange, nRow, "01/01/1980");
							}
							
							dateText.setText(data.get(nRange, nRow));
						}
						
						MagicDocument.add(nRange, nRow, data);
						
						nRange = i;
						row.setText(""+(nRow));
						range.setText(ranges[nRange]);
						
						if (choice == 0)
							currentData.setText(data.get(nRange, nRow));
						else if (choice == 1)
						{
							if (data.get(nRange, nRow) != null && !data.get(nRange, nRow).toString().matches(""))
								phenoChoice.setSelection(Integer.parseInt(data.get(nRange, nRow).toString()));
							else
								phenoChoice.setSelection(0);
						}
						else if (choice == 2)
						{

							String temp1 = data.get(nRange, nRow);
							if (temp != null || !temp1.matches("01/01/1980"))
							{
								month = Integer.parseInt(temp1.substring(0, temp1.indexOf("/"))) - 1;
								temp1 = temp1.substring(temp1.indexOf("/") + 1);
								day = Integer.parseInt(temp1.substring(0, temp1.indexOf("/")));
								temp1 = temp1.substring(temp1.indexOf("/") + 1);
								year = Integer.parseInt(temp1);
								setDate(month, day, year);
								date.updateDate(year, month, day);
								shedding.setChecked(true);
							}
							else
							{
								//data.add(nRange, nRow, "0");
								if (temp.matches("0"))
									date.updateDate(1980, 01, 01);
								else
									date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
								
								shedding.setChecked(false);
							}
							
							dateText.setText(data.get(nRange, nRow));
						}
						
						break;
					}
					else if (i + 1 == ranges.length)
					{
						//System.out.println("could not find");
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	public void setUpButton(final int choice)
	{
		nextRange = (Button)findViewById(R.id.nextRange);
    	
    	nextRange.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//				//System.out.println(nRange + "::" + nRow);
				if (choice == 0)
					data.add(nRange, nRow, currentData.getText().toString());
				else if (choice == 1)
					data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
				else if (choice == 2)
				{
					if (shedding.isChecked())
					{
						month = date.getMonth();
						day = date.getDayOfMonth();
						year = date.getYear();
						
						setDate(month, day, year);
					}
					else
					{
						data.add(nRange, nRow, "01/01/1980");
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				MagicDocument.add(nRange, nRow, data);
				
				if (nRange >= 0 && nRange + 1 < eRange)
					nRange++;
				else
					nRange = 0;
				
				range.setText(ranges[nRange]);
				
				if (choice == 0)
					currentData.setText(data.get(nRange, nRow));
				else if (choice == 1)
				{
					if (data.get(nRange, nRow) != null && !data.get(nRange, nRow).toString().matches(""))
						phenoChoice.setSelection(Integer.parseInt(data.get(nRange, nRow).toString()));
					else
						phenoChoice.setSelection(0);
				}
				else if (choice == 2)
				{
					String temp = data.get(nRange, nRow);
					
					if (temp != null && (!temp.matches("01/01/1980") && !(temp.length() == 1)))
					{
						month = Integer.parseInt(temp.substring(0, temp.indexOf("/"))) - 1;
						temp = temp.substring(temp.indexOf("/") + 1);
						day = Integer.parseInt(temp.substring(0, temp.indexOf("/")));
						temp = temp.substring(temp.indexOf("/") + 1);
						year = Integer.parseInt(temp);
						setDate(month, day, year);
						date.updateDate(year, month, day);
						shedding.setChecked(true);
					}
					else
					{
						//data.add(nRange, nRow, "0");
						if (temp.matches("0"))
							date.updateDate(1980, 01, 01);
						else
							date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
						
						shedding.setChecked(false);
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				rangeChoice.setSelection(nRange);
			}
    	});
    	
    	backRange = (Button)findViewById(R.id.backRange);
    	
    	backRange.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (choice == 0)
					data.add(nRange, nRow, currentData.getText().toString());
				else if (choice == 1)
					data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
				else if (choice == 2)
				{
					if (shedding.isChecked())
					{
						month = date.getMonth();
						day = date.getDayOfMonth();
						year = date.getYear();
						
						setDate(month, day, year);
					}
					else
					{
						data.add(nRange, nRow, "01/01/1980");
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				MagicDocument.add(nRange, nRow, data);
				
				if (nRange >=1 && nRange <= eRange)
					nRange--;
				else
					nRange = eRange - 1;
				
				range.setText(ranges[nRange]);
				
				if (choice == 0)
					currentData.setText(data.get(nRange, nRow));
				else if (choice == 1)
				{
					if (data.get(nRange, nRow) != null && !data.get(nRange, nRow).toString().matches(""))
						phenoChoice.setSelection(Integer.parseInt(data.get(nRange, nRow).toString()));
					else
						phenoChoice.setSelection(0);
				}
				else if (choice == 2)
				{
					String temp = data.get(nRange, nRow);
					
					if (temp != null && (!temp.matches("01/01/1980") && !(temp.length() == 1)))
					{
						month = Integer.parseInt(temp.substring(0, temp.indexOf("/"))) - 1;
						temp = temp.substring(temp.indexOf("/") + 1);
						day = Integer.parseInt(temp.substring(0, temp.indexOf("/")));
						temp = temp.substring(temp.indexOf("/") + 1);
						year = Integer.parseInt(temp);
						setDate(month, day, year);
						date.updateDate(year, month, day);
						shedding.setChecked(true);
					}
					else
					{
						//data.add(nRange, nRow, "0");
						if (temp.matches("0"))
							date.updateDate(1980, 01, 01);
						else
							date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
						
						shedding.setChecked(false);
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				rangeChoice.setSelection(nRange);
			}
    	});
    	
    	nextRow = (Button)findViewById(R.id.nextRow);
    	
    	nextRow.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (choice == 0)
					data.add(nRange, nRow, currentData.getText().toString());
				else if (choice == 1)
					data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
				else if (choice == 2)
				{
					if (shedding.isChecked())
					{
						month = date.getMonth();
						day = date.getDayOfMonth();
						year = date.getYear();
						
						setDate(month, day, year);
					}
					else
					{
						data.add(nRange, nRow, "01/01/1980");
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				MagicDocument.add(nRange, nRow, data);
				
				if (nRow >= 1 && nRow + 1 < eRow)
					nRow++;
				else
					nRow = 1;
				
				//System.out.println(nRow);
				row.setText(""+nRow);
				
				if (choice == 0)
					currentData.setText(data.get(nRange, nRow));
				else if (choice == 1)
				{
					if (data.get(nRange, nRow) != null && !data.get(nRange, nRow).toString().matches(""))
						phenoChoice.setSelection(Integer.parseInt(data.get(nRange, nRow).toString()));
					else
						phenoChoice.setSelection(0);
				}
				else if (choice == 2)
				{
					String temp = data.get(nRange, nRow);
					
					if (temp != null && (!temp.matches("01/01/1980") && !(temp.length() == 1)))
					{
						month = Integer.parseInt(temp.substring(0, temp.indexOf("/"))) - 1;
						temp = temp.substring(temp.indexOf("/") + 1);
						day = Integer.parseInt(temp.substring(0, temp.indexOf("/")));
						temp = temp.substring(temp.indexOf("/") + 1);
						year = Integer.parseInt(temp);
						setDate(month, day, year);
						date.updateDate(year, month, day);
						shedding.setChecked(true);
					}
					else
					{
						//data.add(nRange, nRow, "0");
						if (temp.matches("0"))
							date.updateDate(1980, 01, 01);
						else
							date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
						
						shedding.setChecked(false);
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				rowChoice.setSelection(nRow - 1);
			}
    	});
    	
    	backRow = (Button)findViewById(R.id.backRow);
    	
    	backRow.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (choice == 0)
					data.add(nRange, nRow, currentData.getText().toString());
				else if (choice == 1)
					data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
				else if (choice == 2)
				{
					if (shedding.isChecked())
					{
						month = date.getMonth();
						day = date.getDayOfMonth();
						year = date.getYear();
						
						setDate(month, day, year);
					}
					else
					{
						data.add(nRange, nRow, "01/01/1980");
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				MagicDocument.add(nRange, nRow, data);
				
				//goes to next row, grabs data and puts it in the correct place
				if (nRow >=2 && nRow <= eRow)
					nRow--;
				else
					nRow = eRow - 1;
				
				//System.out.println(nRow + "::" + eRow);
				
				row.setText(""+nRow);
				
				if (choice == 0)
					currentData.setText(data.get(nRange, nRow));
				else if (choice == 1)
				{
					if (data.get(nRange, nRow) != null && !data.get(nRange, nRow).toString().matches(""))
						phenoChoice.setSelection(Integer.parseInt(data.get(nRange, nRow).toString()));
					else
						phenoChoice.setSelection(0);
					
					//System.out.println(data.get(nRange, nRow));
				}
				else if (choice == 2)
				{
					String temp = data.get(nRange, nRow);
					
					if (temp != null && (!temp.matches("01/01/1980") && !(temp.length() == 1)))
					{
						month = Integer.parseInt(temp.substring(0, temp.indexOf("/"))) - 1;
						temp = temp.substring(temp.indexOf("/") + 1);
						day = Integer.parseInt(temp.substring(0, temp.indexOf("/")));
						temp = temp.substring(temp.indexOf("/") + 1);
						year = Integer.parseInt(temp);
						setDate(month, day, year);
						date.updateDate(year, month, day);
						shedding.setChecked(true);
					}
					else
					{
						//data.add(nRange, nRow, "0");
						if (temp.matches("0"))
							date.updateDate(1980, 01, 01);
						else
							date.updateDate(Integer.parseInt(currentDate.substring(1, 2)), Integer.parseInt(currentDate.substring(2, 4)), Integer.parseInt(currentDate.substring(4)));
						
						shedding.setChecked(false);
					}
					
					dateText.setText(data.get(nRange, nRow));
				}
				
				rowChoice.setSelection(nRow - 1);
			}
    	});
    	
    	save = (Button)findViewById(R.id.saveCurrent);
    	
    	save.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (choice == 0)
					data.add(nRange, nRow, currentData.getText().toString());
				else if (choice == 1)
					data.add(nRange, nRow, phenoChoice.getSelectedItem().toString());
				else if (choice == 2)
				{
					if (shedding.isChecked())
					{
						month = date.getMonth();
						day = date.getDayOfMonth();
						year = date.getYear();
						
						setDate(month, day, year);
					}
					else
					{
						data.add(nRange, nRow, "01/01/1980");
					}
				}
				
				MagicDocument.add(nRange, nRow, data);
			}
    	});
    	
    	back = (Button)findViewById(R.id.saveBack);
    	
    	back.setOnClickListener(new Button.OnClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
				alertDialog.setTitle("Save File Name");
	            alertDialog.setMessage("Enter File Name (including .xls)");
	            final EditText input = new EditText(MainActivity.this);
	            input.setText(newFileName);
	            alertDialog.setView(input);
	            alertDialog.setButton("Save", new DialogInterface.OnClickListener() {
	            	   public void onClick(DialogInterface dialog, int which) {
	            		      // TODO Add your code for the button here.
	            		   	  	String newFileName = input.getText().toString();
		            		   	if (!newFileName.contains(".xls"))
	         		   	  			newFileName += ".xls";
		            		  
		            		   	//System.out.println(newFileName);
		            		   	MagicDocument.newSaveName(newFileName);
		            		   	MagicDocument.add(nRange, nRow, data);
	            		   	  
		            		   	//Set settings
	            				Editor edit = pref.edit();
	            				edit.putString("stringIn", "");
	            				edit.putString("previous", newFileName);
	            				edit.commit();
	            				
	            		   	  	finish();
	            		   }
	            		});
	            //alertDialog.setIcon(R.drawable.icon);
	            alertDialog.show();
			}
    	});
	}
	
	public void setDate(int m, int d, int y)
	{
		String date = (m+1) + "/" + d + "/" + y;
		data.add(nRange, nRow, date);
		dateText.setText(months[m] + " " + d + ", " + y);
	}
}


